package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 过滤器
 */
public class AuthorizeFilter2 implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、拿到请求体，响应体
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2、判断该请请求否是登录
        if (request.getURI().getPath().contains("/login")) {
            //登录直接放行
            return chain.filter(exchange);
        }
        try {
            //非登录请求判断请求头是否含有token 会有很多，拿到第一个
            String token = request.getHeaders().getFirst("token");
            if (token == null) {
                //没有权限 返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //结束方法
                return response.setComplete();
            } else {
                //解析token
                Claims claims = AppJwtUtil.getClaimsBody(token);
                //判断是否过期 1 2 过期   0 -1 有效
                int res = AppJwtUtil.verifyToken(claims);
                if (res == 1 || res == 2) {
                    //过期
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
                Object userId = claims.get("id");
                //在request的请求头的hearders中token中解析出来的userId
                ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders -> httpHeaders.add("userId", userId.toString())).build();
                //重置header
                exchange.mutate().request(httpRequest).build();
            }

        } catch (Exception e) {
            //伪造token就会抛异常
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 能到这，基本上就是通过了
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
